# -*- coding: utf-8 -*-

"""
京东配送API SDK Python使用示例
"""

import time
import sys
import os

# 添加上级目录到路径，以便导入SDK
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from jingdong_api_sdk import JingdongApiSDK, OrderData, MerchantInfo


def main():
    print("=== 京东配送API SDK Python示例 ===\n")
    
    # 配置SDK
    sdk = JingdongApiSDK(
        app_key="your_app_key",
        app_secret="your_app_secret",
        merchant_no="your_merchant_no",
        sandbox_mode=True,  # 测试环境
        timeout=30,
        enable_log=True
    )
    
    try:
        # 1. 测试连接
        print("1. 测试API连接...")
        result = sdk.test_connection()
        if result.success:
            print("✓ API连接正常")
        else:
            print(f"✗ API连接失败: {result.message}")
        print()
        
        # 2. 申请成为配送商
        print("2. 申请成为配送商...")
        merchant_info = MerchantInfo(
            merchant_name="测试商户",
            merchant_phone="13800138000",
            merchant_address="北京市朝阳区测试地址",
            business_license="91110000000000000X",
            contact_person="张三",
            contact_phone="13800138001",
            merchant_type="1"
        )
        
        result = sdk.apply_merchant(merchant_info)
        if result.success:
            print("✓ 申请提交成功")
            apply_id = result.data.get('apply_id', 'N/A') if result.data else 'N/A'
            print(f"申请ID: {apply_id}")
        else:
            print(f"✗ 申请失败: {result.message}")
        print()
        
        # 3. 查询配送商状态
        print("3. 查询配送商状态...")
        result = sdk.query_merchant_status()
        if result.success:
            print("✓ 查询成功")
            status = result.data.get('status', 'N/A') if result.data else 'N/A'
            print(f"状态: {status}")
        else:
            print(f"✗ 查询失败: {result.message}")
        print()
        
        # 4. 预下单（获取运费）
        print("4. 预下单获取运费...")
        pre_order_data = {
            'cargo_type': '1',
            'cargo_weight': 1000,  # 1kg
            'cargo_num': '1',
            'cargo_price': '100.00',
            'pickup_info': {
                'address': '北京市朝阳区发货地址',
                'lng': 116.397470,
                'lat': 39.908860
            },
            'delivery_info': {
                'address': '北京市海淀区收货地址',
                'lng': 116.307490,
                'lat': 39.981730
            },
            'expected_pickup_time': int(time.time()) + 3600,  # 1小时后取货
            'expected_delivery_time': int(time.time()) + 7200  # 2小时后送达
        }
        
        result = sdk.pre_order(pre_order_data)
        if result.success:
            print("✓ 询价成功")
            delivery_fee = result.data.get('delivery_fee', 'N/A') if result.data else 'N/A'
            print(f"配送费: {delivery_fee} 元")
        else:
            print(f"✗ 询价失败: {result.message}")
        print()
        
        # 5. 创建配送订单
        print("5. 创建配送订单...")
        order_data = OrderData(
            order_id=f"TEST_ORDER_{int(time.time())}",
            recipient_name="李四",
            recipient_phone="13900139000",
            recipient_address="北京市海淀区收货地址123号",
            recipient_lng=116.307490,
            recipient_lat=39.981730,
            total_weight=1.0,  # 1kg
            sender_lng=116.397470,
            sender_lat=39.908860,
            sender_name="王五",
            sender_phone="13800138000",
            sender_address="北京市朝阳区发货地址456号",
            trade_order_source=1,
            service_code="STANDARD",
            prebook=0,
            operator_name="王五",
            ext_info={'remark': '测试订单，请小心配送'},
            order_remark="测试订单备注",
            shop_remark="商户备注信息"
        )
        
        result = sdk.create_order(order_data)
        jd_order_id = None
        if result.success:
            print("✓ 订单创建成功")
            jd_order_id = result.data.get('jd_order_id') if result.data else None
            print(f"京东订单号: {jd_order_id or 'N/A'}")
        else:
            print(f"✗ 订单创建失败: {result.message}")
        print()
        
        # 6. 查询订单状态
        if jd_order_id:
            print("6. 查询订单状态...")
            result = sdk.query_order(order_data.order_id, jd_order_id)
            if result.success:
                print("✓ 查询成功")
                status = result.data.get('status', 'N/A') if result.data else 'N/A'
                rider_name = result.data.get('rider_name', 'N/A') if result.data else 'N/A'
                print(f"订单状态: {status}")
                print(f"骑手信息: {rider_name}")
            else:
                print(f"✗ 查询失败: {result.message}")
            print()
            
            # 7. 查询骑手位置
            print("7. 查询骑手位置...")
            result = sdk.query_rider_location(order_data.order_id)
            if result.success:
                print("✓ 查询成功")
                if result.data:
                    rider_lng = result.data.get('rider_lng', 'N/A')
                    rider_lat = result.data.get('rider_lat', 'N/A')
                    print(f"骑手位置: {rider_lng}, {rider_lat}")
            else:
                print(f"✗ 查询失败: {result.message}")
            print()
        
        # 8. 查询可配送范围
        print("8. 查询可配送范围...")
        result = sdk.query_service_area('116.397470', '39.908860')
        if result.success:
            print("✓ 查询成功")
            deliverable = result.data.get('deliverable') if result.data else None
            print(f"可配送: {'是' if deliverable else '否'}")
        else:
            print(f"✗ 查询失败: {result.message}")
        print()
        
        # 9. 查询历史订单列表
        print("9. 查询历史订单列表...")
        condition = {
            'page_size': 10,
            'page_no': 1,
            'start_time': '2023-01-01 00:00:00',
            'end_time': '2023-12-31 23:59:59'
        }
        
        result = sdk.query_order_list(condition)
        if result.success:
            print("✓ 查询成功")
            orders = result.data.get('orders', []) if result.data else []
            print(f"订单数量: {len(orders)}")
        else:
            print(f"✗ 查询失败: {result.message}")
        print()
        
        # 10. 验证回调签名（示例）
        print("10. 验证回调签名...")
        callback_data = {
            'out_order_id': 'TEST_ORDER_123456',
            'jd_order_id': 'JD_123456789',
            'order_status': '20',
            'rider_name': '配送员张三',
            'rider_phone': '13700137000'
        }
        
        # 生成签名进行验证
        test_signature = 'test_signature_here'
        is_valid = sdk.verify_callback(callback_data, test_signature)
        print("✓ 签名验证通过" if is_valid else "✗ 签名验证失败")
        print()
        
    except Exception as e:
        print(f"示例执行异常: {e}")
        import traceback
        traceback.print_exc()
    finally:
        # 关闭资源
        sdk.close()
    
    print("=== 示例执行完成 ===")


if __name__ == "__main__":
    main()
